package ink.xiaobaibai.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import ink.xiaobaibai.autoConfig.roleResources.ResourcesRoleMapping;
import ink.xiaobaibai.common.MyRole;
import ink.xiaobaibai.entity.AdminUser;
import ink.xiaobaibai.entity.Department;
import ink.xiaobaibai.response.ResponseFormat;
import ink.xiaobaibai.service.IAdminUserService;
import ink.xiaobaibai.service.IDepartmentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @description: 部门控制层
 * @author: 小白白
 * @create: 2021-05-26
 **/

@RestController
@RequestMapping("/security/department")
@Slf4j
@CrossOrigin
@Api(tags = "部门接口")
public class SecurityDepartmentController {

    @Autowired
    private IDepartmentService departmentService;

    @Autowired
    private IAdminUserService adminUserService;

    @GetMapping("/list")
    @ApiOperation("部门列表")
    public ResponseFormat list() {
        List<Department> list = this.departmentService.list();
        return ResponseFormat.success(list);
    }

    @PostMapping("/add")
    @ApiOperation("添加部门")
    @ResourcesRoleMapping(resourceName = "部门控制", includeRoleNames = {MyRole.ADMIN})
    public ResponseFormat addDep(@RequestBody String depName) {
        this.departmentService.save(new Department(depName));
        return ResponseFormat.success();
    }

    @DeleteMapping("/delete/{id}")
    @ApiOperation("删除部门")
    @ResourcesRoleMapping(resourceName = "部门控制", includeRoleNames = {MyRole.ADMIN})
    public ResponseFormat deleteDep(@PathVariable("id") Integer id) {
        //旗下是否有人员
        QueryWrapper<AdminUser> q1 = new QueryWrapper<>();
        q1.eq("department_id", id);
        if (this.adminUserService.count(q1) > 0) {
            return ResponseFormat.fail("当前部门下还有人员,不可删除");
        }
        this.departmentService.removeById(id);
        return ResponseFormat.success();
    }

    @PutMapping("/update/{id}")
    @ApiOperation("修改部门名称")
    @ResourcesRoleMapping(resourceName = "部门控制", includeRoleNames = {MyRole.ADMIN})
    public ResponseFormat updateDepName(@PathVariable("id") Integer id,
                                        @RequestBody String depName) {
        UpdateWrapper<Department> u1 = new UpdateWrapper<>();
        u1.set("department_name", depName);
        u1.eq("id", id);
        this.departmentService.update(u1);
        return ResponseFormat.success();
    }

}
